<?php
App::import('Vendor', 'ThumbLib', array('file' => 'ThumbLib.inc.php'));

/**
 * This class using PHPThumb <http://phpthumb.gxdlabs.com> for resize image
 * as the requirement of project
 *
 * @author Dat Nguyen <datnt@evolable.asia>
 */
class ImageUtil {
	protected $_image;
	function __construct($imageDir) {
		$this->_image = PhpThumbFactory::create($imageDir);
		$this->_image->setOptions(array(
			'resizeUp' => true,
		));
	}

	/**
	 * Resize image, if the image have one dimension less than input dimension, using adaptiveResize,
	 * else using crop function
	 *
	 * @param $maxWidth
	 * @param $maxHeight
	 * @return ImageUtil
	 * @throws Exception
	 */
	function extendResize($maxWidth, $maxHeight) {
		try {
			$quadrant = 'L';
			$d = $this->_image->getCurrentDimensions();
			$width = (int)$d['width'];
			if ($width && $maxHeight < $d['height'] * $maxWidth / $width) {
				$quadrant = 'T';
			}
			$this->_image->adaptiveResizeQuadrant($maxWidth, $maxHeight, $quadrant);
		} catch (Exception $e) {
			throw new Exception('Could not resize image');
		}
		return $this;
	}

	/**
	 * Write image to file
	 *
	 * @param $imageDir
	 * @throws Exception
	 */
	function save($imageDir) {
		try {
			$this->_image->save($imageDir);
		} catch (Exception $e) {
			throw new Exception('Could not save image to ' . $imageDir);
		}
	}
}